package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.util.DBUtil;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class CartServiceImpl implements CartService {
    @Override
    public int saveCart(Cart cart) {
        int result = 0;
        CartDao cartDao = new CartDaoImpl();
        try {
            DBUtil.beginTransaction();;
            result = cartDao.saveCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int updateCart(Cart cart) {
        int result = 0;
        CartDao cartDao = new CartDaoImpl();
        try {
            DBUtil.beginTransaction();
            result = cartDao.updateCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public int removeCart(Cart cart) {
        int result = 0;
        CartDao cartDao = new CartDaoImpl();
        try {
            DBUtil.beginTransaction();
            result = cartDao.removeCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public List<Cart> listCart(Cart cart) {
        List<Cart> cartList = null;
        CartDao cartDao = new CartDaoImpl();
        try {
            cartList = cartDao.listCart(cart);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return cartList;
    }
}
